package com.code.question4.client;

import com.alibaba.fastjson.JSON;
import com.code.question4.base.RequestType;
import com.code.question4.base.ResponseType;
import com.code.question4.model.ResponseMessage;
import com.code.question4.model.User;
import com.code.question4.model.UserMessage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * 客户端
 */
public class CustomerClient {
    public static void main(String[] args) {
        //初始化Socket对象及输入输出对象，负责接收服务器消息和输出消息到服务器端的
        Socket s = null;
        PrintStream ps = null;
        BufferedReader br = null;
        try {
            //连接服务器端，端口号指定为8888
            s = new Socket("127.0.0.1", 8888);
            System.out.println("连接服务器成功");
            //获取Socket输出对象
            ps = new PrintStream(s.getOutputStream());
            //获取Socket输入对象
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            //输入账号密码
            System.out.println("请输入账号。。。");
            String name = new BufferedReader(new InputStreamReader(System.in)).readLine();
            System.out.println("请输入密码。。。");
            String password = new BufferedReader(new InputStreamReader(System.in)).readLine();
            //序列化为Json字符串发送到服务器端
            UserMessage um = new UserMessage(RequestType.GET, "login", new User(name, password));
            ps.println(JSON.toJSON(um));
            //接收服务器返回信息，判断输出
            String responseMessage = br.readLine();
            ResponseMessage rm = JSON.parseObject(responseMessage, ResponseMessage.class);
            if (rm.getCode() == ResponseType.SUCCESS) System.out.println("登录成功");
            else System.out.println("登录失败");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                ps.close();
            }
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
